package com.dongbo.recorder.screenrecord.ui.fragment;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.dongbo.recorder.screenrecord.AppLpds;
import com.dongbo.recorder.screenrecord.Constants;
import com.dongbo.recorder.screenrecord.LoadAd;
import com.dongbo.recorder.screenrecord.R;
import com.dongbo.recorder.screenrecord.base.BaseFragment;
import com.dongbo.recorder.screenrecord.bean.AppMarketInfo;
import com.dongbo.recorder.screenrecord.bean.DialogMenuItem;
import com.dongbo.recorder.screenrecord.bean.NetResponse;
import com.dongbo.recorder.screenrecord.bean.UserBean;
import com.dongbo.recorder.screenrecord.dialog.CustomerServiceDialog;
import com.dongbo.recorder.screenrecord.prefrences.PreferencesRepository;
import com.dongbo.recorder.screenrecord.ui.activity.FeedbackActivity;
import com.dongbo.recorder.screenrecord.ui.activity.LoginActivity;
import com.dongbo.recorder.screenrecord.ui.activity.SettingActivity;
import com.dongbo.recorder.screenrecord.ui.activity.VipActivity;
import com.dongbo.recorder.screenrecord.utils.AppMarketUtils;
import com.dongbo.recorder.screenrecord.utils.CleanDataUtils;
import com.dongbo.recorder.screenrecord.utils.NormalListDialog;
import com.dongbo.recorder.screenrecord.utils.OkGoUpdateHttpUtil;
import com.dongbo.recorder.screenrecord.utils.OnOperItemClickL;
import com.dongbo.recorder.screenrecord.widget.GlideCircleTransform;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umeng.analytics.MobclickAgent;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import com.vector.update_app.utils.AppUpdateUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author GuoZi
 * @date :2020/5/5 22:38
 * @description:
 */
public class MyFragment extends BaseFragment {
    @BindView(R.id.my_title)
    LinearLayout myTitle;
    @BindView(R.id.my_logo)
    ImageView myLogo;
    @BindView(R.id.my_name)
    TextView myName;
    @BindView(R.id.my_right)
    ImageView myRight;
    @BindView(R.id.my_vip_time)
    TextView myVipTime;
    @BindView(R.id.tvCacheSize)
    TextView tvCacheSize;
    @BindView(R.id.my_vip_centent)
    TextView myVipCentent;
    @BindView(R.id.my_suggestions)
    LinearLayout my_suggestions;
    @BindView(R.id.my_setting)
    LinearLayout mySetting;
    @BindView(R.id.my_clean)
    LinearLayout myClean;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.my_update)
    LinearLayout myUpdate;
    @BindView(R.id.my_kefu)
    LinearLayout myKefu;
    @BindView(R.id.rl_to_vip)
    RelativeLayout rlToVip;
    @BindView(R.id.root)
    View root;
    @BindView(R.id.express_container)
    FrameLayout mExpressContainer;

    private UpdateAppManager mUpdate;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_my;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        try {
            tvCacheSize.setText(CleanDataUtils.getTotalCacheSize(getContext()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            String verName = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0).versionName;
//        tvVersion.setText(BuildConfig.VERSION_NAME);
            tvVersion.setText("v" + verName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        GradientDrawable gradientDrawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{Color.parseColor("#5298f0"), Color.parseColor("#F5F7FB")});
        root.setBackground(gradientDrawable);

        new LoadAd().initTTSDKConfig(requireActivity(), Constants.ADV_BANNER_ID, new LoadAd.OnAdEventListener() {
            @Override
            public void removeAllViews() {
                mExpressContainer.removeAllViews();
            }

            @Override
            public void onLoadError(int code, String message) {
                mExpressContainer.removeAllViews();
            }

            @Override
            public void addAllViews(View view, float width, float height) {
                mExpressContainer.removeAllViews();
                mExpressContainer.addView(view);
            }

            @Override
            public void closeAd(int position, String value, boolean enforce) {
                mExpressContainer.removeAllViews();
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("MyFragment"); //统计页面("MainScreen"为页面名称，可自定义)
//        MobclickAgent.onPageStart("AfterServiceFragment"); //统计页面("MainScreen"为页面名称，可自定义)
        if (AppLpds.getInstance().isLogin()) {
            refreshUserInfo();
//            bindUserData(AppLpds.getMySp().getUserInfo());
        } else {
            bindUserData(null);
        }


    }

    private void bindUserData(UserBean info) {
        try {
            if (info != null) {
                if (info.isVip()) {
                    myVipTime.setText("VIP到期时间：" + info.getVipEndTime());
                } else {
                    myVipTime.setText("VIP会员享受更多特权");
                }
                myName.setText(!TextUtils.isEmpty(info.getNickname()) ? info.getNickname() : info.getAccount());
            } else {
                myName.setText("去登录");
                myVipTime.setText("VIP会员能享受更多特权");
            }
            Glide.with(getContext()).load(info == null ? "" : info.getAvatar()).transform(new GlideCircleTransform()).placeholder(R.mipmap.default_avatar).error(R.mipmap.default_avatar).into(myLogo);
        } catch (NullPointerException e) {
            e.printStackTrace();
//            LogUtils.e("variable not attached");
        }
    }

    @Override
    protected void initListener() {

    }

    @OnClick({R.id.my_title, R.id.my_vip_centent, R.id.my_suggestions, R.id.my_setting, R.id.my_clean, R.id.my_update, R.id.my_kefu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.my_title:
                if (!AppLpds.getInstance().isLogin()) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                }
                break;
            case R.id.my_vip_centent:
                if (!AppLpds.getInstance().isLogin()) {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                    return;
                }
                startActivity(new Intent(getActivity(), VipActivity.class));
                break;
            case R.id.my_suggestions:
                startActivity(new Intent(getActivity(), FeedbackActivity.class));
//                WebActivity.start(getActivity(), "投诉建议", "http://ymqqkrhy4b8vvpzs.mikecrm.com/CqconDV");
                break;
            case R.id.my_setting:
                startActivity(new Intent(getActivity(), SettingActivity.class));
                break;
            case R.id.my_clean:
                try {
                    CleanDataUtils.clearAllCache(getContext());
                    String size = CleanDataUtils.getTotalCacheSize(getContext());
                    tvCacheSize.setText(size);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.my_update:
                startUpdata();
                break;
            case R.id.my_kefu:
//                showCusSerDialog();
//                startActivity(new Intent(getActivity(), CustomerServiceActivity.class));
                break;
        }
    }

    //检查更新
    private void startUpdata() {
        initUpLoad();
        //检测是否有新版本
        mUpdate.checkNewApp(new UpdateCallback() {
            /**
             * 有新版本
             *
             * @param updateApp        新版本信息
             * @param updateAppManager app更新管理器
             */
            @Override
            public void hasNewApp(UpdateAppBean updateApp, UpdateAppManager updateAppManager) {
                initMarketList();
            }

            /**
             * 网络请求之前
             */
            @Override
            public void onBefore() {

            }

            /**
             * 网路请求之后
             */
            @Override
            public void onAfter() {

            }

            /**
             * 没有新版本
             */
            @Override
            public void noNewApp(String msg) {
                showToast("当前已是最新版本");
            }
        });
    }

    private void initUpLoad() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        Map<String, String> params = new HashMap<String, String>();
        params.put("appKey", Constants.APP_DOWNLOAD_APP_KEY);
        params.put("version", AppUpdateUtils.getVersionName(getActivity().getApplicationContext()));
        mUpdate = new UpdateAppManager.Builder()
                //必须设置，当前Activity
                .setActivity(getActivity())
                //必须设置，实现httpManager接口的对象
                .setHttpManager(new OkGoUpdateHttpUtil())
                //必须设置，更新地址
                .setUpdateUrl(Constants.APP_DOWNLOAD_URL)
                //以下设置，都是可选
                //设置请求方式，默认get
                .setPost(true)
                //添加自定义参数，默认version=1.0.0（app的versionName）；apkKey=唯一表示（在AndroidManifest.xml配置）
                .setParams(params)
                //设置apk下砸路径，默认是在下载到sd卡下/Download/1.0.0/test.apk
                .setTargetPath(path)
                //设置appKey，默认从AndroidManifest.xml获取，如果，使用自定义参数，则此项无效
//                .setAppKey("ab55ce55Ac4bcP408cPb8c1Aaeac179c5f6f")
                .build();
    }

    private void initMarketList() {
        List<AppMarketInfo> marketList = new ArrayList<>();
        //应用宝
//        if (AppMarketUtils.isAvilible(mContext, "com.tencent.android.qqdownloader")) {
        marketList.add(new AppMarketInfo(R.mipmap.ic_launcher, "应用宝", "com.tencent.android.qqdownloader"));
//        }
        //360
//        if (AppMarketUtils.isAvilible(mContext, "com.qihoo.appstore")) {
        marketList.add(new AppMarketInfo(R.mipmap.ic_launcher, "360", "com.qihoo.appstore"));
//        }
        //百度
//        if (AppMarketUtils.isAvilible(mContext, "com.baidu.appsearch")) {
        marketList.add(new AppMarketInfo(R.mipmap.ic_launcher, "百度", "com.baidu.appsearch"));
//        }

        //小米
//        if (AppMarketUtils.isAvilible(mContext, "com.xiaomi.market")) {
        marketList.add(new AppMarketInfo(R.mipmap.ic_launcher, "小米", "com.xiaomi.market"));
//        }

        //豌豆荚
//        if (AppMarketUtils.isAvilible(mContext, "com.wandoujia.phoenix2")) {
        marketList.add(new AppMarketInfo(R.mipmap.ic_launcher, "豌豆荚", "com.wandoujia.phoenix2"));
//        }

        //华为
//        if (AppMarketUtils.isAvilible(mContext, "com.huawei.appmarket")) {
        marketList.add(new AppMarketInfo(R.mipmap.ic_launcher, "华为", "com.huawei.appmarket"));
//        }

        //oppo
//        if (AppMarketUtils.isAvilible(mContext, "com.oppo.market")) {
        marketList.add(new AppMarketInfo(R.mipmap.ic_launcher, "oppo", "com.oppo.market"));
//        }
        //vivo
//        if (AppMarketUtils.isAvilible(mContext, "com.bbk.appstore")) {
        marketList.add(new AppMarketInfo(R.mipmap.ic_launcher, "vivo", "com.bbk.appstore"));
//        }

        openTypeListDialog(marketList);
    }

    //列表选择
    private void openTypeListDialog(final List<AppMarketInfo> mList) {
        final NormalListDialog dialog = new NormalListDialog(getContext(), getTypeMenuList(mList));
        dialog.title("请选择应用市场")//
                .titleTextSize_SP(18)//
                .titleBgColor(getContext().getResources().getColor(R.color.color_main))//
                .lvBgColor(getContext().getResources().getColor(R.color.white)).itemTextColor(getContext().getResources().getColor(R.color.ff7f000000))//
                .itemTextSize(15)//
                .cornerRadius(5)//
                .layoutAnimation(null).widthScale(0.8f)//
                .showAnim(null).dismissAnim(null).show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                dialog.dismiss();
                if (AppMarketUtils.isAvilible(getContext(), mList.get(position).getPackageName())) {
                    AppMarketUtils.launchAppDetail(getContext(), getActivity().getPackageName(), mList.get(position).getPackageName());
                } else {
//                    anzAPPDialog(mList.get(position).getName(), mList.get(position).getPackageName());
                    Toast.makeText(getContext(), "您还没有安装" + mList.get(position).getName() + "应用市场", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    private ArrayList<DialogMenuItem> getTypeMenuList(List<AppMarketInfo> mList) {
        ArrayList<DialogMenuItem> cms = new ArrayList<>();
        for (AppMarketInfo c : mList) {
            DialogMenuItem dmi = new DialogMenuItem(c.getName(), 0);
            cms.add(dmi);
        }
        return cms;
    }

    /**
     * 客服
     */
    private void showCusSerDialog() {
        CustomerServiceDialog mDialog = new CustomerServiceDialog(getContext(), R.style.recharge_pay_dialog, new CustomerServiceDialog.OnDialogEventListener() {
            @Override
            public void onClicked(String QQ) {
                try {
                    String url = "mqqwpa://im/chat?chat_type=wpa&uin=3133881878";
                    //uin是发送过去的qq号码
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("您还没有安装QQ，请先安装软件");
                }
            }

        });
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.show();
    }

    private void refreshUserInfo() {
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(Constants.BASE_URL + "/app/user/getUserInfo")
                .addHeader("Authorization", AppLpds.getInstance().getToken()).get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        bindUserData(AppLpds.getInstance().getLoginData());
//                    Tt.show(getActivity(), e.getMessage());
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String data = response.body().string();
                if (TextUtils.isEmpty(data)) {
                    getActivity().runOnUiThread(() -> {
                        PreferencesRepository.getDefaultInstance().setString(Constants.PREFERENCE_USER_DATA, "");
                        PreferencesRepository.getDefaultInstance().setString(Constants.PREFERENCE_USER_TOKEN, "");
                        bindUserData(null);
                    });
                    return;
                }
//                Log.i("TAG__+", body);
//                Log.i("TAG__+", data);
                NetResponse<UserBean> info = null;
                try {
                    info = new Gson().fromJson(data, new TypeToken<NetResponse<UserBean>>() {
                    }.getType());
                    if (null == info) {
                        return;
                    }
                    if (info.getStatusCode() == Constants.TOKEN_CODE) {
                        PreferencesRepository.getDefaultInstance().setString(Constants.PREFERENCE_USER_DATA, "");
                        PreferencesRepository.getDefaultInstance().setString(Constants.PREFERENCE_USER_TOKEN, "");
                        bindUserData(null);
                        return;
                    }
                    if (info.getStatusCode() == 200 && info.getData() != null) {
                        UserBean finalInfo = info.getData();
                        AppLpds.getMySp().setUserInfo(info.getData());
                        PreferencesRepository.getDefaultInstance().setString(Constants.PREFERENCE_USER_DATA, new Gson().toJson(info.getData()));
                        if (getActivity() != null) {
                            getActivity().runOnUiThread(() -> bindUserData(finalInfo));
                        }
                    } else {
                        if (getActivity() != null) {
                            getActivity().runOnUiThread(() -> {
                                bindUserData(AppLpds.getInstance().getLoginData());
                            });
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    getActivity().runOnUiThread(() -> {
                        PreferencesRepository.getDefaultInstance().setString(Constants.PREFERENCE_USER_DATA, "");
                        PreferencesRepository.getDefaultInstance().setString(Constants.PREFERENCE_USER_TOKEN, "");
                        bindUserData(null);
                    });

                }

            }
        });
    }


    // Fragment页面onResume函数重载
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("MyFragment");
    }

}
